package org.ktm.web.tags;

import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import org.ktm.quantity.SystemOfUnits;
import org.ktm.utils.DateUtils;
import org.ktm.utils.Localizer;
import org.ktm.utils.PropertyUtils;

public class Functions {

    public static String getText(String name) {
        return Localizer.getMessage(name);
    }

    public static Object getBeanProperty(Object obj, String name) {
        return PropertyUtils.getProperty(obj, name);
    }

    public static Integer length(Collection<?> cols) {
        return cols.size();
    }

    public static Boolean isEmpty(String text) {
        if (text != null && !text.isEmpty()) { return false; }
        return true;
    }

    public static Boolean isEmptyCollection(Collection<?> colls) {
        return colls.size() <= 0;
    }

    public static Boolean equal(String val1, String val2) {
        return val1.equals(val2);
    }

    public static String getEnumValues(String enumName) {
        String result = "";
        Class<?> clz;
        try {
            clz = Class.forName(enumName);
            Object[] consts = clz.getEnumConstants();
            for (Object obj : consts) {
                result += obj.toString();
                if (obj != consts[consts.length - 1]) {
                    result += ",";
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getAllUnits() {
        String result = SystemOfUnits.units[0].getMetricName();
        for (int i = 1; i < SystemOfUnits.units.length; i++) {
            result += "," + SystemOfUnits.units[i].getMetricName();
        }
        return result;
    }

    public static String getToDay() {
        try {
            return DateUtils.formatDate(new Date());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }
    /*
     *           SI         BINARY
     * 0:        0 B        0 B
     * 27:       27 B       27 B
     * 999:      999 B      999 B
     * 1000:     1.0 kB     1000 B
     * 1023:     1.0 kB     1023 B
     * 1024:     1.0 kB    1.0 KiB
     * 1728:     1.7 kB    1.7 KiB
     * 110592:   110.6 kB  108.0 KiB
     * 7077888:     7.1 MB    6.8 MiB
     * 452984832:   453.0 MB  432.0 MiB
     * 28991029248:    29.0 GB   27.0 GiB
     * 1855425871872:     1.9 TB    1.7 TiB
     * 9223372036854775807:     9.2 EB    8.0 EiB   (Long.MAX_VALUE)
     */
    public static String humanReadableByteCount(long bytes, boolean si) {
        int unit = si ? 1000 : 1024;
        if (bytes < unit) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }
}
